package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;

import config.AlipayConfig;

/**
 * 支付成功之后 同步回调的页面通知 有可能通知失败
 
 回调参数: "同步通知返回的参数:  {charset=utf-8, out_trade_no=202003230524342434, method=alipay.trade.page.pay.return, total_amount=0.01, sign=DCMTHbezLULulXQ0RxL0US3FEGGHKEctCU3HFznYsXvrhOHhmR4WQfEjQMqLG8Zp2qz16gSf9i4hkOaqchf2+80dAakveHcAfbLdY7U1Tf7Yi24Ygq/LmulOIroBvmcj0WgOozZ32fRAXkkMHfns/QXSBBaAqkO10/TaDv+PAgbq2kRRf44BHRRQKbqXlRMyI/gQ0MA0/T+xpcAF3fwKo47Sm9O5oNIQ2FL5qhW7zCFZ63+6m+hoiVZvdnvePuefa4MhvEaRSdOgV2n9B5q9IWNpgSLIgLGNWm4Zp8OIN7S7fXctF6xL483cyhaClV2tAbBWZObQv/KNfdVPJ9PXUw==, trade_no=2020032322001442990500961507, auth_app_id=2016092000556654, version=1.0, app_id=2016092000556654, sign_type=RSA2, seller_id=2088102176505735, timestamp=2020-03-23 17:25:33}"

 * 验证支付信息是否匹配,如订单 金额 商家
 *  显示支付成功就行了
 *  
 *  业务逻辑(后台订单信息修改,通知扣款短信等等)处理请勿在该页面执行
 *  
 *  参考  return_url.jsp 中的代码
 */
@WebServlet("/AlipayReturnURL")
public class AlipayReturnURL extends HttpServlet {
	private static final long serialVersionUID = 1L;
      
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out= response.getWriter();
		
		
		System.out.println("------------------支付宝同步处理url ------------------------");
		
		//获取支付宝GET过来反馈信息
		Map<String,String> params = new HashMap<String,String>();
		Map<String,String[]> requestParams = request.getParameterMap();
		for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			//乱码解决，这段代码在出现乱码时使用
			//valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
			params.put(name, valueStr);
		}
		
		String json = JSON.toJSONString("同步通知返回的参数:  "+params);
		System.out.println("回调参数: "+ json);
		
		//验证支付订单是否合法
		boolean signVerified;
		
		try {
			signVerified = AlipaySignature.rsaCheckV1(params
																					, AlipayConfig.alipay_public_key
																					, AlipayConfig.charset
																					, AlipayConfig.sign_type);
			//支付信息 私钥/公钥对得上 appid也对得上
			if(signVerified) {
				//商户订单号
				String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
			
				//支付宝交易号
				String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
			
				//付款金额
				String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");
				
				//out.println("trade_no:"+trade_no+"<br/>out_trade_no:"+out_trade_no+"<br/>total_amount:"+total_amount);
				request.setAttribute("msg", "trade_no:"+trade_no+"<br/>out_trade_no:"+out_trade_no+"<br/>total_amount:"+total_amount);
				
				request.getRequestDispatcher("success.jsp").forward(request, response);
				
			}else {
				out.println("验签失败");
			}
			
		} catch (AlipayApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} //调用SDK验证签名

		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
